//
//  JMSetViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/8/31.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMSetViewController.h"
#import "JMFeedbackViewController.h"
#import "JMAppNetworkClient.h"
#import "AppDelegate.h"
#import "JMBrowserViewController.h"
#import "JMLoginViewController.h"


@interface JMSetViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIButton *signOutBtn;
@end

@implementation JMSetViewController


- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        tableView.frame = self.view.bounds;
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
        [_dataArray addObjectsFromArray:@[@"意见反馈",@"清除缓存",@"关于我们"]];
    }
    return _dataArray;
}
- (UIButton *)signOutBtn
{
    if (!_signOutBtn) {
        UIButton *button = [[UIButton alloc]init];
        [button setTitle:@"退出登录" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(signOutButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setBackgroundImage:[UIImage imageNamed:@"projectImage.bundle/signOut_image"] forState:UIControlStateNormal];
        button.frame = CGRectMake(UI_SCREEN_WITH/2.0 - UI_SCREEN_WITH *0.8125/2.0, 40, UI_SCREEN_WITH *0.8125, UI_SCREEN_WITH *0.109375);
        _signOutBtn = button;
    }
    return _signOutBtn;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title =@"设置";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WITH, 100)];
    self.tableView.tableFooterView = view;
    [view addSubview:self.signOutBtn];
}


#pragma mark  tableView delegate dasouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }
    return 1;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * str=@"ID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.font = [UIFont systemFontOfSize:UI_SCREEN_WITH *0.0375];
    if(indexPath.section == 0){
        cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
    }else{
        cell.textLabel.text = [self.dataArray objectAtIndex:2];
    }
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0 && indexPath.row == 0){
//        JMFeedbackViewController *vc = [JMFeedbackViewController new];
//        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 1 && indexPath.row == 0){
        JMConfigure *cf = [JMConfigure sharedConfigureManger];
        if(![cf.user.state isEqualToString:@"1"]){
            [self gotoLogin];
            return;
        }
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [JMAppNetworkClient token_WithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                        JMBrowserViewController *vc =[JMBrowserViewController new];
                        vc.url =[NSURL URLWithString:[JMAppNetworkClient aboutUsUrl]];
                        [self.navigationController pushViewController:vc animated:NO];
                }else{
                    [self gotoLogin];
                }
            }];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)gotoLogin{
    JMLoginViewController *vc = [JMLoginViewController new];
    JMNavigationController *nav = [[JMNavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:^{
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UI_SCREEN_WITH *0.119475;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return UI_SCREEN_HEIGHT *0.026408;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}


#pragma mark  tui chu deng lu
-(void)signOutButtonClick:(id)sender{

//    user	int
//    token	char(16)
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [JMAppNetworkClient signOutWithINfo:dict complete:^(id data, NSError *error) {
            //获得Document的路径
            if([data[@"status"] integerValue] == 1){
                [JMTools showAlertView:self.view message:data[@"message"]];
                NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];//拓展名可以自己随便取
                NSFileManager *defaultManager = [NSFileManager defaultManager];
                if ([defaultManager isDeletableFileAtPath:path]) {
                    [defaultManager removeItemAtPath:path error:nil];
                }
                [self.navigationController popToRootViewControllerAnimated:NO];
                UIWindow * window = [[UIApplication sharedApplication] keyWindow];
                JMMainViewController *vc = [[JMMainViewController alloc]init];
                JMNavigationController *nav = [[JMNavigationController alloc]initWithRootViewController:vc];
                window.rootViewController = nav;
                
            }else{
                [JMTools showAlertView:self.view message:data[@"message"]];
            }
            [JMTools hiddenAlerView:self.view];
        }];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
